package com.atguigu.flink.chapter07;

import com.atguigu.flink.bean.WaterSensor;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

public class Flink07_Window_Aggregate {
    public static class Avg {
        public Integer vcSum = 0;
        public Long count = 0L;

        public Double avg() {
            return this.vcSum * 1.0 / count;
        }
    }

    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(2);

        env
                .socketTextStream("hadoop162",9999)
                .map(line -> {
                    String[] data = line.split(",");
                    return new WaterSensor(data[0], Long.valueOf(data[1]), Integer.valueOf(data[2]));
                })
                .keyBy(WaterSensor::getId)
                .window(TumblingProcessingTimeWindows.of(Time.seconds(4)))
                .aggregate(
                        new AggregateFunction<WaterSensor, Avg, Double>() {
                            // 创建累加器： 初始化一个累加器
                            @Override
                            public Avg createAccumulator() {
                                System.out.println("Flink07_Window_Aggregate.createAccumulator");
                                return new Avg();
                            }

                            // 对传入的值进行累加
                            @Override
                            public Avg add(WaterSensor value, Avg acc) {
                                System.out.println("Flink07_Window_Aggregate.add");
                                acc.vcSum += value.getVc();
                                acc.count++;
                                return acc;
                            }

                            // 返回最终的结果
                            @Override
                            public Double getResult(Avg acc) {
                                System.out.println("Flink07_Window_Aggregate.getResult");
                                return acc.avg();
                            }

                            // 合并累加器. 这个方法只有当窗口是会话窗口的时候才会触发
                            @Override
                            public Avg merge(Avg a, Avg b) {
                                System.out.println("Flink07_Window_Aggregate.merge");
                                return null;
                            }
                        },
                        new ProcessWindowFunction<Double, String, String, TimeWindow>() {
                            @Override
                            public void process(String key, Context ctx, Iterable<Double> elements, Collector<String> out) throws Exception {
                                Double result = elements.iterator().next();
                                out.collect(key + " 平均水位： " + result);
                            }
                        }
                )
                .print();

        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
